import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { teamSocketManager } from '@/utils/teamSocketManager'
import { useAuthStore } from '@/stores/auth'
import { useEncryptionStore } from '@/stores/encryption'
import { MessageEncryption } from '@/utils/encryption/MessageEncryption'
import { ElMessage } from 'element-plus'
import teamMessageApi, {
  type TeamMessageDTO,
  type MessageStatus,
  type QueueInfo
} from '@/api/teamMessage'
import {
  EncryptionStatus
} from '@/utils/encryption'

/**
 * 团队聊天状态管理（支持端到端加密）
 */
export const useTeamChatStore = defineStore('teamChat', () => {
  const authStore = useAuthStore()
  const encryptionStore = useEncryptionStore()
  
  // 连接状态
  const isConnected = ref(false)
  const connectionState = ref(teamSocketManager.ConnectionState.DISCONNECTED)
  const reconnectAttempts = ref(0)
  
  // 当前活跃团队
  const activeTeamId = ref<number | null>(null)
  
  // 团队消息缓存 (teamId -> messages[])
  const teamMessages = ref<Record<number, TeamMessageDTO[]>>({})

  // 团队在线成员缓存 (teamId -> members[])
  const teamOnlineMembers = ref<Record<number, any[]>>({})

  // 消息分页状态 (teamId -> pageInfo)
  const messagePageInfo = ref<Record<number, {
    currentPage: number
    totalPages: number
    hasMore: boolean
    loading: boolean
  }>>({})
  
  // 未读消息计数 (teamId -> count)
  const unreadCounts = ref<Record<number, number>>({})

  // RabbitMQ队列状态管理
  const queueStatus = ref<{
    enabled: boolean
    connected: boolean
    stats: {
      routingSuccess: number
      routingFailure: number
      retryCount: number
      deadLetterCount: number
    }
  }>({
    enabled: false,
    connected: false,
    stats: {
      routingSuccess: 0,
      routingFailure: 0,
      retryCount: 0,
      deadLetterCount: 0
    }
  })

  // 消息队列信息缓存 (messageId -> queueInfo)
  const messageQueueInfo = ref<Record<string, QueueInfo>>({})

  // 加密相关状态
  const encryptionEnabled = ref(true) // 是否启用加密
  const messageEncryptionStatus = ref<Record<string, EncryptionStatus>>({}) // 消息加密状态
  const decryptionCache = ref<Record<string, { content: string; fileName?: string; timestamp: number }>>({}) // 解密缓存
  const encryptionErrors = ref<Record<string, string>>({}) // 加密错误记录

  // 计算属性：当前团队消息（自动解密）
  const currentTeamMessages = computed(() => {
    if (!activeTeamId.value) return []
    const messages = teamMessages.value[activeTeamId.value] || []

    // 如果加密未启用，直接返回原始消息
    if (!encryptionEnabled.value) {
      return messages
    }

    const currentUserId = authStore.user?.id

    // 对加密消息进行解密处理
    return messages.map(message => {
      if (!message.isEncrypted || !message.iv || !message.encryptionAlgorithm) {
        return message // 明文消息直接返回
      }

      // 如果是自己发送的消息，检查是否有本地明文缓存
      if (message.senderId === currentUserId) {
        // 检查是否是临时消息（刚发送的）
        if (typeof message.id === 'string' && message.id.startsWith('temp_')) {
          return message // 临时消息直接显示明文
        }

        // 对于已保存的自己的消息，也检查解密缓存
        const cacheKey = `${message.id}_${message.teamId}`
        const cached = decryptionCache.value[cacheKey]

        if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
          return {
            ...message,
            content: cached.content,
            fileName: cached.fileName || message.fileName
          }
        }

        // 如果没有缓存，触发解密（自己的消息也需要解密，因为从数据库加载的是密文）
        triggerAsyncDecryption(message)
        return {
          ...message,
          content: '[正在解密...]'
        }
      }

      // 其他人的消息：检查解密缓存
      const cacheKey = `${message.id}_${message.teamId}`
      const cached = decryptionCache.value[cacheKey]

      if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
        // 返回解密后的消息
        return {
          ...message,
          content: cached.content,
          fileName: cached.fileName || message.fileName
        }
      }

      // 如果没有缓存，触发异步解密
      triggerAsyncDecryption(message)
      return {
        ...message,
        content: '[正在解密...]'
      }
    })
  })
  
  // 计算属性：当前团队在线成员
  const currentTeamOnlineMembers = computed(() => {
    if (!activeTeamId.value) return []
    return teamOnlineMembers.value[activeTeamId.value] || []
  })
  
  // 计算属性：连接状态信息
  const connectionStatus = computed(() => {
    switch (connectionState.value) {
      case teamSocketManager.ConnectionState.CONNECTED:
        return { text: '已连接', color: 'success', icon: 'success' }
      case teamSocketManager.ConnectionState.CONNECTING:
        return { text: '连接中...', color: 'warning', icon: 'loading' }
      case teamSocketManager.ConnectionState.RECONNECTING:
        return { text: `重连中(${reconnectAttempts.value})...`, color: 'warning', icon: 'loading' }
      case teamSocketManager.ConnectionState.FAILED:
        return { text: '连接失败', color: 'danger', icon: 'error' }
      default:
        return { text: '未连接', color: 'info', icon: 'info' }
    }
  })

  /**
   * 初始化团队Socket连接
   */
  const initSocket = async () => {
    console.log('🔍 检查认证状态:', {
      isAuthenticated: authStore.isAuthenticated,
      token: !!authStore.token,
      user: !!authStore.user,
      userId: authStore.user?.id
    })

    if (!authStore.isAuthenticated) {
      console.warn('⚠️ 用户未登录，跳过团队Socket初始化')
      return
    }

    try {
      const userId = authStore.user?.id
      if (!userId) {
        throw new Error('无法获取用户ID')
      }

      await teamSocketManager.connect(userId)
      setupSocketListeners()
      console.log('✅ 团队Socket初始化成功')
      
    } catch (error) {
      console.error('❌ 团队Socket初始化失败:', error)
      ElMessage.error('团队协作连接失败，请刷新页面重试')
    }
  }

  /**
   * 清理Socket事件监听器
   */
  const cleanupSocketListeners = () => {
    if (listenersSetup) {
      console.log('🧹 清理Socket事件监听器')
      teamSocketManager.offConnectionStateChange('teamChatStore')
      teamSocketManager.off('new_team_message')
      teamSocketManager.off('message_sent')
      teamSocketManager.off('message_queued')
      teamSocketManager.off('message_delivered')
      teamSocketManager.off('message_failed')
      teamSocketManager.off('queue_status_update')
      teamSocketManager.off('team_online_members')
      teamSocketManager.off('member_online_status')
      teamSocketManager.off('member_joined_team')
      teamSocketManager.off('member_left_team')
      teamSocketManager.off('joined_team')
      teamSocketManager.off('typing_indicator')
      teamSocketManager.off('stop_typing_indicator')
      listenersSetup = false
    }
  }

  /**
   * 断开团队Socket连接
   */
  const disconnectSocket = () => {
    cleanupSocketListeners()
    teamSocketManager.disconnect()
    isConnected.value = false
    connectionState.value = teamSocketManager.ConnectionState.DISCONNECTED
    activeTeamId.value = null
    console.log('🔌 团队Socket连接已断开')
  }

  // 标记是否已设置监听器
  let listenersSetup = false

  /**
   * 设置Socket事件监听器
   */
  const setupSocketListeners = () => {
    // 避免重复设置监听器
    if (listenersSetup) {
      console.log('⚠️ Socket监听器已设置，跳过重复设置')
      return
    }

    console.log('🔧 设置Socket事件监听器')

    // 连接状态变化
    teamSocketManager.onConnectionStateChange('teamChatStore', (state: string, attempts: number) => {
      connectionState.value = state
      reconnectAttempts.value = attempts
      isConnected.value = state === teamSocketManager.ConnectionState.CONNECTED
    })

    // 新团队消息
    teamSocketManager.on('new_team_message', (message: any) => {
      console.log('📨 收到new_team_message事件:', message)
      const teamId = message.teamId

      // 如果是自己发送的消息，直接忽略（应该通过message_sent事件处理）
      if (message.senderId === authStore.user?.id) {
        console.log('⚠️ 收到自己发送的消息，忽略处理（应该通过message_sent事件处理）')
        return
      }

      // 确保团队消息数组存在
      if (!teamMessages.value[teamId]) {
        teamMessages.value[teamId] = []
      }

      // 检查消息是否已存在（防止重复）
      const existingMessage = teamMessages.value[teamId].find(m => m.id === message.id)
      if (existingMessage) {
        console.log('⚠️ 消息已存在，跳过添加:', message.id)
        return
      }

      // 如果是加密消息，触发异步解密
      if (message.isEncrypted) {
        triggerAsyncDecryption(message)
      }

      // 添加消息
      teamMessages.value[teamId].push(message)
      console.log('✅ 其他用户消息添加成功，当前消息数:', teamMessages.value[teamId].length)

      // 如果不是当前活跃团队，增加未读计数
      if (teamId !== activeTeamId.value) {
        unreadCounts.value[teamId] = (unreadCounts.value[teamId] || 0) + 1
      }
    })

    // 消息发送确认
    teamSocketManager.on('message_sent', (data: any) => {
      console.log('✅ 收到消息发送确认:', data)
      updateMessageStatus(data.messageId, 'sent', data)
    })

    // 消息进入队列确认（RabbitMQ扩展）
    teamSocketManager.on('message_queued', (data: any) => {
      console.log('📤 消息已进入队列:', data)
      updateMessageStatus(data.messageId, 'queued', data)

      // 更新队列信息
      if (data.queueInfo) {
        messageQueueInfo.value[data.messageId.toString()] = {
          queuedAt: data.queueInfo.queuedAt || Date.now(),
          retryCount: data.queueInfo.retryCount || 0,
          routingStrategy: data.queueInfo.routingStrategy
        }
      }
    })

    // 消息投递确认（RabbitMQ扩展）
    teamSocketManager.on('message_delivered', (data: any) => {
      console.log('📨 消息已投递:', data)
      updateMessageStatus(data.messageId, 'delivered', data)

      // 更新队列信息
      const messageKey = data.messageId.toString()
      if (messageQueueInfo.value[messageKey]) {
        messageQueueInfo.value[messageKey].processedAt = Date.now()
      }
    })

    // 消息发送失败（RabbitMQ扩展）
    teamSocketManager.on('message_failed', (data: any) => {
      console.error('❌ 消息发送失败:', data)
      updateMessageStatus(data.messageId, 'failed', data)

      // 更新重试信息
      const messageKey = data.messageId.toString()
      if (messageQueueInfo.value[messageKey]) {
        messageQueueInfo.value[messageKey].retryCount = data.retryCount || 0
      }

      // 显示错误提示
      ElMessage.error(`消息发送失败: ${data.error || '未知错误'}`)
    })

    // 队列状态更新（RabbitMQ扩展）
    teamSocketManager.on('queue_status_update', (data: any) => {
      console.log('📊 队列状态更新:', data)

      queueStatus.value = {
        enabled: data.enabled || false,
        connected: data.connected || false,
        stats: {
          routingSuccess: data.stats?.routingSuccess || 0,
          routingFailure: data.stats?.routingFailure || 0,
          retryCount: data.stats?.retryCount || 0,
          deadLetterCount: data.stats?.deadLetterCount || 0
        }
      }
    })

    listenersSetup = true

    // 团队在线成员
    teamSocketManager.on('team_online_members', (data: any) => {
      const teamId = data.teamId
      teamOnlineMembers.value[teamId] = data.members || []
    })

    // 成员在线状态变更
    teamSocketManager.on('member_online_status', (data: any) => {
      const teamId = data.teamId
      const userId = data.userId
      const isOnline = data.isOnline
      
      if (!teamOnlineMembers.value[teamId]) {
        teamOnlineMembers.value[teamId] = []
      }
      
      if (isOnline) {
        // 用户上线 - 获取最新的在线成员列表
        teamSocketManager.getTeamOnlineMembers(teamId)
      } else {
        // 用户下线 - 从在线成员列表中移除
        teamOnlineMembers.value[teamId] = teamOnlineMembers.value[teamId].filter(
          member => member.userId !== userId
        )
      }
    })
  }

  /**
   * 加入团队
   */
  const joinTeam = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      ElMessage.warning('团队协作连接未建立，请稍后重试')
      return
    }

    activeTeamId.value = teamId
    teamSocketManager.joinTeam(teamId)
    
    // 确保团队消息数组存在
    if (!teamMessages.value[teamId]) {
      teamMessages.value[teamId] = []
    }
    
    // 重置未读计数
    unreadCounts.value[teamId] = 0
    
    // 获取团队在线成员
    setTimeout(() => {
      teamSocketManager.getTeamOnlineMembers(teamId)
    }, 500)
  }

  /**
   * 离开团队
   */
  const leaveTeam = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      return
    }

    teamSocketManager.leaveTeam(teamId)
    
    if (activeTeamId.value === teamId) {
      activeTeamId.value = null
    }
  }

  /**
   * 更新消息状态的辅助方法
   */
  const updateMessageStatus = (messageId: string | number, status: MessageStatus, data?: any) => {
    // 查找并更新消息状态
    Object.keys(teamMessages.value).forEach(teamId => {
      const messages = teamMessages.value[parseInt(teamId)]
      if (messages) {
        const message = messages.find(m =>
          m.id === messageId ||
          m.id.toString() === messageId.toString() ||
          (m.messageStatus === 'sending' && status === 'sent') // 兼容旧逻辑
        )
        if (message) {
          console.log(`🔄 更新消息状态: ${message.id} -> ${status}`)
          message.messageStatus = status

          // 如果是发送确认，更新真实ID并缓存明文内容
          if (status === 'sent' && data?.messageId && message.id.toString().startsWith('temp_')) {
            const oldId = message.id
            const newId = data.messageId

            // 如果原消息是明文但启用了加密，将其内容缓存到解密缓存中
            if (!message.isEncrypted && encryptionEnabled.value) {
              const cacheKey = `${newId}_${message.teamId}`
              decryptionCache.value[cacheKey] = {
                content: message.content,
                fileName: message.fileName,
                timestamp: Date.now()
              }
              console.log('💾 缓存发送消息的明文内容:', cacheKey)

              // 更新消息为加密状态，因为服务器存储的是加密内容
              message.isEncrypted = true
              if (data?.iv) message.iv = data.iv
              if (data?.encryptionAlgorithm) message.encryptionAlgorithm = data.encryptionAlgorithm
              if (data?.keyVersion) message.keyVersion = data.keyVersion
            }

            message.id = newId
          }

          // 更新时间戳
          if (data?.timestamp) {
            message.timestamp = data.timestamp
          }

          // 更新队列信息
          if (data?.queueInfo) {
            message.queueInfo = data.queueInfo
          }
        }
      }
    })
  }

  /**
   * 获取消息队列信息
   */
  const getMessageQueueInfo = (messageId: string | number): QueueInfo | null => {
    return messageQueueInfo.value[messageId.toString()] || null
  }

  /**
   * 重试失败的消息
   */
  const retryFailedMessage = async (messageId: string | number) => {
    const messageKey = messageId.toString()
    const queueInfo = messageQueueInfo.value[messageKey]
    if (!queueInfo) {
      ElMessage.error('找不到消息队列信息')
      return false
    }

    try {
      // 通过Socket发送重试请求
      teamSocketManager.emit('retry_message', { messageId: messageKey })

      // 更新重试次数
      queueInfo.retryCount = (queueInfo.retryCount || 0) + 1

      ElMessage.info('正在重试发送消息...')
      return true
    } catch (error) {
      console.error('重试消息失败:', error)
      ElMessage.error('重试失败')
      return false
    }
  }

  /**
   * 发送团队消息（支持加密）
   */
  const sendTeamMessage = async (teamId: number, content: string, messageType: string = 'text', fileInfo?: any) => {
    console.log('🔍 准备发送消息，检查连接状态...')

    if (!teamSocketManager.isConnected()) {
      console.error('❌ Socket连接检查失败，尝试重新连接...')

      // 尝试重新连接
      try {
        await initSocket()
        if (!teamSocketManager.isConnected()) {
          ElMessage.warning('团队协作连接未建立，请稍后重试')
          return false
        }
      } catch (error) {
        ElMessage.error('连接失败，请刷新页面重试')
        return false
      }
    }

    if (!content.trim()) {
      ElMessage.warning('消息内容不能为空')
      return false
    }

    try {
      // 准备加密数据
      let encryptedContent = content
      let encryptedFileName = fileInfo?.fileName
      let encryptionData: { iv?: string; algorithm?: string; keyVersion?: number } = {}

      // 如果启用加密，则加密消息内容和文件名
      if (encryptionEnabled.value && encryptionStore.isAvailable) {
        try {
          console.log('🔐 开始加密消息内容...')

          // 加密消息内容
          const contentEncrypted = await encryptionStore.encryptMessage(content, teamId)
          encryptedContent = contentEncrypted.ciphertext
          encryptionData.iv = contentEncrypted.iv
          encryptionData.algorithm = contentEncrypted.algorithm
          encryptionData.keyVersion = 1

          // 如果有文件名，使用相同的IV进行加密
          if (fileInfo?.fileName) {
            // 获取团队密钥
            const teamKey = await encryptionStore.getTeamKey(teamId)
            // 使用消息内容相同的IV加密文件名
            const fileNameEncrypted = await MessageEncryption.encryptWithIV(
              fileInfo.fileName,
              teamKey,
              contentEncrypted.iv
            )
            encryptedFileName = fileNameEncrypted.ciphertext
            console.log('🔐 文件名加密完成，使用相同IV:', contentEncrypted.iv)
          }

          console.log('✅ 消息加密完成')
        } catch (error) {
          console.error('❌ 消息加密失败:', error)
          ElMessage.error('消息加密失败，请重试')
          return false
        }
      }

      // 创建临时消息对象（立即显示，显示明文）
      const tempMessage: TeamMessageDTO = {
        id: `temp_${Date.now()}`, // 临时ID
        teamId,
        senderId: authStore.user?.id || 0,
        senderName: authStore.user?.username || '',
        senderAvatar: authStore.user?.avatarUrl,
        content, // 显示原始明文内容
        messageType: messageType as 'text' | 'image' | 'file',
        timestamp: Date.now(),
        messageStatus: 'sending' as MessageStatus,
        // 临时消息标记为未加密，因为内容是明文
        isEncrypted: false
      }

      // 初始化队列信息
      messageQueueInfo.value[tempMessage.id.toString()] = {
        retryCount: 0,
        routingStrategy: messageType === 'file' || messageType === 'image' ? 'topic' : 'direct'
      }

      // 如果是文件消息，添加文件信息
      if (fileInfo) {
        tempMessage.fileName = fileInfo.fileName // 显示原始文件名
        tempMessage.fileSize = fileInfo.fileSize
        tempMessage.fileUrl = fileInfo.fileUrl
      }

      // 立即添加到本地消息列表
      if (!teamMessages.value[teamId]) {
        teamMessages.value[teamId] = []
      }
      teamMessages.value[teamId].push(tempMessage)
      console.log('✅ 临时消息添加成功，等待服务器确认')

      // 发送消息到服务器（发送加密后的内容）
      const sendData = {
        teamId,
        content: encryptedContent, // 发送加密后的内容
        messageType,
        fileName: encryptedFileName, // 发送加密后的文件名
        fileSize: fileInfo?.fileSize,
        fileUrl: fileInfo?.fileUrl,
        iv: encryptionData.iv,
        encryptionAlgorithm: encryptionData.algorithm,
        keyVersion: encryptionData.keyVersion,
        isEncrypted: encryptionEnabled.value
      }

      teamSocketManager.sendTeamMessage(teamId, sendData.content, messageType, {
        ...fileInfo,
        fileName: sendData.fileName,
        iv: sendData.iv,
        encryptionAlgorithm: sendData.encryptionAlgorithm,
        keyVersion: sendData.keyVersion,
        isEncrypted: sendData.isEncrypted
      })
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      ElMessage.error('发送消息失败')
      return false
    }
  }

  /**
   * 解密消息内容
   */
  const decryptMessage = async (message: TeamMessageDTO): Promise<TeamMessageDTO> => {
    // 如果消息未加密或已经解密过，直接返回
    if (!message.isEncrypted || !message.iv || !message.encryptionAlgorithm) {
      return message
    }

    // 检查解密缓存
    const cacheKey = `${message.id}_${message.teamId}`
    const cached = decryptionCache.value[cacheKey]
    if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) { // 5分钟缓存
      return {
        ...message,
        content: cached.content,
        fileName: cached.fileName || message.fileName
      }
    }

    try {
      console.log('🔓 开始解密消息:', message.id)

      // 解密消息内容
      const encryptedData = {
        ciphertext: message.content,
        iv: message.iv,
        algorithm: message.encryptionAlgorithm
      }

      const decryptedContent = await encryptionStore.decryptMessage(encryptedData, message.teamId)

      // 解密文件名（如果有）
      let decryptedFileName = message.fileName
      if (message.fileName && message.messageType !== 'text') {
        try {
          const encryptedFileName = {
            ciphertext: message.fileName,
            iv: message.iv,
            algorithm: message.encryptionAlgorithm
          }
          decryptedFileName = await encryptionStore.decryptMessage(encryptedFileName, message.teamId)
        } catch (error) {
          console.warn('⚠️ 文件名解密失败，使用原始文件名:', error)
        }
      }

      // 缓存解密结果
      decryptionCache.value[cacheKey] = {
        content: decryptedContent,
        fileName: decryptedFileName,
        timestamp: Date.now()
      }

      console.log('✅ 消息解密成功:', message.id)

      return {
        ...message,
        content: decryptedContent,
        fileName: decryptedFileName
      }

    } catch (error) {
      console.error('❌ 消息解密失败:', message.id, error)
      encryptionErrors.value[cacheKey] = error instanceof Error ? error.message : '解密失败'

      // 返回错误提示消息
      return {
        ...message,
        content: '[消息解密失败]',
        messageStatus: 'failed' as MessageStatus
      }
    }
  }

  /**
   * 批量解密消息列表
   */
  const decryptMessages = async (messages: TeamMessageDTO[]): Promise<TeamMessageDTO[]> => {
    if (!encryptionEnabled.value || !encryptionStore.isAvailable) {
      return messages
    }

    const decryptPromises = messages.map(message => decryptMessage(message))
    return await Promise.all(decryptPromises)
  }

  /**
   * 异步解密消息（不阻塞UI）
   */
  const triggerAsyncDecryption = async (message: TeamMessageDTO) => {
    if (!message.isEncrypted || !message.iv || !message.encryptionAlgorithm) {
      return
    }

    const cacheKey = `${message.id}_${message.teamId}`

    // 避免重复解密
    if (decryptionCache.value[cacheKey]) {
      return
    }

    try {
      console.log('🔓 异步解密消息:', message.id)

      // 解密消息内容
      const encryptedData = {
        ciphertext: message.content,
        iv: message.iv,
        algorithm: message.encryptionAlgorithm
      }

      const decryptedContent = await encryptionStore.decryptMessage(encryptedData, message.teamId)

      // 解密文件名（如果有）
      let decryptedFileName = message.fileName
      if (message.fileName && message.messageType !== 'text') {
        try {
          const encryptedFileName = {
            ciphertext: message.fileName,
            iv: message.iv,
            algorithm: message.encryptionAlgorithm
          }
          decryptedFileName = await encryptionStore.decryptMessage(encryptedFileName, message.teamId)
        } catch (error) {
          console.warn('⚠️ 文件名解密失败，使用原始文件名:', error)
        }
      }

      // 缓存解密结果
      decryptionCache.value[cacheKey] = {
        content: decryptedContent,
        fileName: decryptedFileName,
        timestamp: Date.now()
      }

      console.log('✅ 异步解密完成:', message.id)

    } catch (error) {
      console.error('❌ 异步解密失败:', message.id, error)
      encryptionErrors.value[cacheKey] = error instanceof Error ? error.message : '解密失败'
    }
  }

  /**
   * 初始化团队聊天
   */
  const initTeamChat = async (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      await initSocket()
    }

    joinTeam(teamId)

    // 加载历史消息
    await loadMoreMessages(teamId)
  }

  /**
   * 离开团队聊天
   */
  const leaveTeamChat = (teamId: number) => {
    leaveTeam(teamId)
  }

  /**
   * 加载更多消息
   */
  const loadMoreMessages = async (teamId: number) => {
    try {
      // 获取当前分页信息
      const pageInfo = messagePageInfo.value[teamId] || {
        currentPage: 0,
        totalPages: 0,
        hasMore: true,
        loading: false
      }

      if (pageInfo.loading || !pageInfo.hasMore) {
        return
      }

      // 设置加载状态
      messagePageInfo.value[teamId] = { ...pageInfo, loading: true }

      // 调用API获取历史消息
      const response = await teamMessageApi.getTeamMessages(teamId, pageInfo.currentPage, 20)

      if (response.code === 200 && response.data) {
        const { messages, totalPages, currentPage, hasNext } = response.data

        // 确保团队消息数组存在
        if (!teamMessages.value[teamId]) {
          teamMessages.value[teamId] = []
        }

        // 对消息进行异步解密处理
        messages.forEach(message => {
          if (message.isEncrypted) {
            triggerAsyncDecryption(message)
          }
        })

        // 将新消息添加到开头（历史消息）
        teamMessages.value[teamId].unshift(...messages.reverse())

        // 更新分页信息
        messagePageInfo.value[teamId] = {
          currentPage: currentPage + 1,
          totalPages,
          hasMore: hasNext,
          loading: false
        }

        console.log(`✅ 加载团队${teamId}历史消息成功，获取${messages.length}条消息`)
      }
    } catch (error) {
      console.error('加载历史消息失败:', error)

      // 重置加载状态
      if (messagePageInfo.value[teamId]) {
        messagePageInfo.value[teamId].loading = false
      }

      ElMessage.error('加载历史消息失败')
      throw error
    }
  }

  /**
   * 搜索消息
   */
  const searchMessages = async (teamId: number, keyword: string, page: number = 0) => {
    try {
      if (!keyword.trim()) {
        return []
      }

      // 调用API搜索消息
      const response = await teamMessageApi.searchTeamMessages(teamId, keyword.trim(), page, 20)

      if (response.code === 200 && response.data) {
        console.log(`✅ 搜索团队${teamId}消息成功，关键词：${keyword}，找到${response.data.messages.length}条消息`)
        return response.data.messages
      }

      return []
    } catch (error) {
      console.error('搜索消息失败:', error)
      ElMessage.error('搜索消息失败')
      throw error
    }
  }

  /**
   * 获取最近消息
   */
  const getRecentMessages = async (teamId: number, limit: number = 10) => {
    try {
      const response = await teamMessageApi.getRecentMessages(teamId, limit)

      if (response.code === 200 && response.data) {
        console.log(`✅ 获取团队${teamId}最近消息成功，获取${response.data.length}条消息`)
        return response.data
      }

      return []
    } catch (error) {
      console.error('获取最近消息失败:', error)
      throw error
    }
  }

  /**
   * 发送正在输入指示
   */
  const sendTypingIndicator = (teamId: number) => {
    if (!teamSocketManager.isConnected()) return

    teamSocketManager.emit('typing_start', { teamId })
  }

  /**
   * 停止正在输入指示
   */
  const stopTypingIndicator = (teamId: number) => {
    if (!teamSocketManager.isConnected()) return

    teamSocketManager.emit('typing_stop', { teamId })
  }

  /**
   * 获取团队在线成员
   */
  const getTeamOnlineMembers = (teamId: number) => {
    if (!teamSocketManager.isConnected()) {
      return
    }

    teamSocketManager.getTeamOnlineMembers(teamId)
  }

  /**
   * 获取团队未读消息数
   */
  const getUnreadCount = (teamId: number) => {
    return unreadCounts.value[teamId] || 0
  }

  /**
   * 清除团队未读消息数
   */
  const clearUnreadCount = (teamId: number) => {
    unreadCounts.value[teamId] = 0
  }

  // 计算属性：是否有更多历史消息
  const hasMoreHistory = computed(() => {
    if (!activeTeamId.value) return false
    const pageInfo = messagePageInfo.value[activeTeamId.value]
    return pageInfo ? pageInfo.hasMore : true
  })

  // 计算属性：历史消息加载状态
  const loadingHistory = computed(() => {
    if (!activeTeamId.value) return false
    const pageInfo = messagePageInfo.value[activeTeamId.value]
    return pageInfo ? pageInfo.loading : false
  })

  // 计算属性：当前团队信息
  const currentTeam = computed(() => {
    // TODO: 从团队store获取当前团队信息
    return null
  })

  return {
    // 状态
    isConnected,
    connectionState,
    connectionStatus,
    reconnectAttempts,
    activeTeamId,
    teamMessages,
    teamOnlineMembers,
    unreadCounts,
    currentTeamMessages,
    currentTeamOnlineMembers,
    hasMoreHistory,
    loadingHistory,
    currentTeam,
    messagePageInfo,

    // RabbitMQ队列状态
    queueStatus,
    messageQueueInfo,

    // 加密相关状态
    encryptionEnabled,
    messageEncryptionStatus,
    decryptionCache,
    encryptionErrors,

    // Socket管理器
    teamSocketManager,

    // 方法
    initSocket,
    disconnectSocket,
    joinTeam,
    leaveTeam,
    sendTeamMessage,
    updateMessageStatus,
    getMessageQueueInfo,
    retryFailedMessage,
    getTeamOnlineMembers,
    getUnreadCount,
    clearUnreadCount,
    initTeamChat,
    leaveTeamChat,
    loadMoreMessages,
    searchMessages,
    getRecentMessages,
    sendTypingIndicator,
    stopTypingIndicator,

    // 加密相关方法
    decryptMessage,
    decryptMessages
  }
})
